package com.atguigu.demo;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/8
 */
public class NotSafeDemo {

    public static void main(String[] args) {
        hashMapSafeDemo();
    }

    private static void arrayListSafeDemo() {
//        List<String> list = new ArrayList<>();
//        List<String> list = new Vector<>();
//        List<String> list = Collections.synchronizedList(new ArrayList<>());
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 6));
                System.out.println(Thread.currentThread().getName() + "----" + list);
            }, "t" + i).start();
        }
    }

    private static void hashMapSafeDemo() {
//        Map<String, String> map = new HashMap<>();
//        Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
        Map<String, String> map = new ConcurrentHashMap<>();

        for (int i = 0; i < 30; i++) {
            int finalI = i;
            new Thread(() -> {
                map.put(String.valueOf(finalI), UUID.randomUUID().toString().substring(0, 6));
                System.out.println(Thread.currentThread().getName() + "----" + map);
            }, "t" + i).start();
        }
    }

    private static void hashSetSafeDemo() {
//        Set<String> set = new HashSet<>();
//        Set<String> set = Collections.synchronizedSet(new HashSet<>());
        Set<String> set = new CopyOnWriteArraySet<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 6));
                System.out.println(Thread.currentThread().getName() + "----" + set);
            }, "t" + i).start();
        }
    }
}
